<template>
  <el-dialog
    title="商品信息"
    :visible.sync="visible"
    width="900px"
    :before-close="handleClose"
    append-to-body
    class="compact-dialog"
  >
    <div class="good-form-container">
      <div class="form-section">
        <el-form ref="form" :model="form" :rules="rules" label-width="100px" size="small">
          <el-tabs v-model="activeTab" class="main-tabs" type="border-card">
            <!-- 基础信息 -->
            <el-tab-pane label="商品信息" name="basic">
              <div class="tab-header">
                <i class="el-icon-goods tab-icon" />
                <span class="tab-title">基础商品信息</span>
                <div class="tab-line" />
              </div>

              <div class="form-grid">
                <!-- 左侧信息 -->
                <div class="form-column">
                  <el-form-item label="商品类型" prop="isStandard" required>
                    <div class="input-with-icon">
                      <i class="el-icon-s-flag form-item-icon" />
                      <el-radio-group v-model="form.isStandard">
                        <el-radio :label="1">标品</el-radio>
                        <el-radio :label="2">非标品</el-radio>
                      </el-radio-group>
                    </div>
                  </el-form-item>

                  <el-form-item label="商品名称" prop="name">
                    <div class="input-with-icon">
                      <i class="el-icon-collection-tag form-item-icon" />
                      <el-input
                        v-model="form.name"
                        placeholder="请输入商品名称"
                        class="enhanced-input"
                        @input="handleNameChange"
                      />
                    </div>
                    <div class="form-tip">
                      <i class="el-icon-info tip-icon" />
                      <span>建议命名方式为"品牌+品名+商品规格"</span>
                    </div>
                  </el-form-item>

                  <el-form-item label="产地" prop="origin">
                    <div class="input-with-icon">
                      <i class="el-icon-location form-item-icon" />
                      <el-input
                        v-model="form.origin"
                        placeholder="请输入，不超过12字"
                        class="enhanced-input"
                        maxlength="12"
                      />
                    </div>
                  </el-form-item>

                  <el-form-item label="商品类目" prop="categoryIds">
                    <div class="input-with-icon">
                      <i class="el-icon-menu form-item-icon" />
                      <el-cascader
                        v-model="form.categoryIds"
                        :options="productCategoryTreeData"
                        :props="{ value: 'categoryId', label: 'categoryName', children: 'children' }"
                        placeholder="请选择类目"
                        class="enhanced-input"
                        filterable
                      />
                    </div>
                  </el-form-item>

                  <el-form-item label="品牌" prop="brand">
                    <div class="input-with-icon">
                      <i class="el-icon-trophy form-item-icon" />
                      <div class="brand-input-group">
                        <el-select
                          v-model="form.brand"
                          filterable
                          placeholder="请选择品牌"
                        >
                          <el-option
                            v-for="item in (brand || [])"
                            :key="item.dictValue"
                            :label="item.dictLabel"
                            :value="item.dictLabel"
                          />
                        </el-select>
                        <!-- <el-button type="text" icon="el-icon-plus" class="add-btn">新增</el-button> -->
                      </div>
                    </div>
                  </el-form-item>

                  <el-form-item label="渠道类目" prop="category">
                    <el-cascader
                      v-model="form.meituanAttr"
                      :options="meituanTreeData"
                      :props="{ value: 'id', label: 'name', children: 'children' }"
                      placeholder="请选择渠道类目"
                      filterable
                    />
                  </el-form-item>

                  <el-form-item label="商品要点" prop="sellingPoints">
                    <el-input
                      v-model="form.sellingPoints"
                      placeholder="请输入15字以内的商品要点"
                      maxlength="15"
                      show-word-limit
                    />
                  </el-form-item>

                  <el-form-item label="商品描述" prop="description">
                    <el-input
                      v-model="form.description"
                      type="textarea"
                      placeholder="请输入200字以内的商品描述"
                      maxlength="200"
                      show-word-limit
                      :rows="3"
                    />
                  </el-form-item>
                </div>

                <!-- 右侧图片区域 -->
                <div class="form-column">
                  <el-form-item label="商品图片" prop="images">
                    <div class="upload-group">
                      <div class="upload-item">
                        <div class="upload-label">主图展示</div>
                        <el-upload
                          :action="uploadImgUrl"
                          list-type="picture-card"
                          :auto-upload="true"
                          :file-list="form.mainImage"
                          :on-success="(res, file) => handleUploadSuccess(res, file, 'mainImage')"
                          :on-remove="(file, fileList) => handleRemove(file, fileList, 'mainImage')"
                          :headers="headers"
                          :limit="3"
                          class="compact-upload"
                        >
                          <i class="el-icon-plus" />
                        </el-upload>
                      </div>

                      <div class="upload-item">
                        <div class="upload-label">包装展示</div>
                        <el-upload
                          :action="uploadImgUrl"
                          list-type="picture-card"
                          :auto-upload="true"
                          :file-list="form.mainImageTwo"
                          :on-success="(res, file) => handleUploadSuccess(res, file, 'mainImageTwo')"
                          :on-remove="(file, fileList) => handleRemove(file, fileList, 'mainImageTwo')"
                          :headers="headers"
                          :limit="3"
                          class="compact-upload"
                        >
                          <i class="el-icon-plus" />
                        </el-upload>
                      </div>

                      <div class="upload-item">
                        <div class="upload-label">原料展示</div>
                        <el-upload
                          :action="uploadImgUrl"
                          list-type="picture-card"
                          :auto-upload="true"
                          :file-list="form.mainImageThree"
                          :on-success="(res, file) => handleUploadSuccess(res, file, 'mainImageThree')"
                          :on-remove="(file, fileList) => handleRemove(file, fileList, 'mainImageThree')"
                          :headers="headers"
                          :limit="3"
                          class="compact-upload"
                        >
                          <i class="el-icon-plus" />
                        </el-upload>
                      </div>
                    </div>
                    <div class="upload-tip">建议上传3-5张高质量图片，提升商品曝光量</div>
                  </el-form-item>

                  <el-form-item label="封面视频">
                    <el-upload
                      class="video-uploader"
                      action="#"
                      :show-file-list="false"
                      :on-change="handleVideoChange"
                    >
                      <div v-if="form.video" class="video-container">
                        <video :src="form.video" controls />
                      </div>
                      <div v-else class="upload-video-placeholder">
                        <i class="el-icon-plus" />
                        <div>上传视频</div>
                      </div>
                    </el-upload>
                    <div class="upload-tip">支持10MB以内mp4格式</div>
                  </el-form-item>
                </div>
              </div>
            </el-tab-pane>

            <!-- 规格信息 -->
            <el-tab-pane label="规格信息" name="spec">
              <div class="tab-header">
                <i class="el-icon-s-grid tab-icon" />
                <span class="tab-title">商品规格信息</span>
                <div class="tab-line" />
              </div>

              <div class="spec-header">
                <div class="spec-type">
                  <i class="el-icon-s-grid spec-icon" />
                  <el-radio-group v-model="form.specType">
                    <el-radio :label="1">多规格商品</el-radio>
                  </el-radio-group>
                </div>
                <div class="button-group">
                  <el-button
                    type="primary"
                    class="add-spec-btn"
                    size="small"
                    @click="addSpec"
                  >
                    <i class="el-icon-plus"></i>
                    <span>添加规格</span>
                  </el-button>
                </div>
              </div>

              <div class="spec-table-wrapper">
                <div class="spec-table-header">
                  <div class="header-title-wrapper">
                    <i class="el-icon-s-order" />
                    <span class="header-title">规格列表</span>
                  </div>
                  <div class="header-actions">
                    <el-tooltip content="表格内容可左右滚动查看" placement="top">
                      <i class="el-icon-warning-outline" />
                    </el-tooltip>
                  </div>
                </div>
                <el-table
                  :data="form.productSkus"
                  border
                  size="small"
                  class="spec-table"
                  style="width: 100%"
                  :header-cell-style="{ background: 'var(--spec-header-bg)', color: '#2a5082', fontWeight: '600' }"
                  :row-class-name="getRowClass"
                >
                  <el-table-column prop="specification" label="规格名称" min-width="120">
                    <template slot="header">
                      <div class="custom-table-header">
                        <i class="el-icon-tickets header-icon" />
                        <span>规格名称</span>
                      </div>
                    </template>
                    <template slot-scope="scope">
                      <el-input
                        v-model="scope.row.specification"
                        placeholder="规格名称"
                        class="spec-input"
                      />
                    </template>
                  </el-table-column>

                  <el-table-column label="重量" min-width="150">
                    <template slot="header">
                      <div class="custom-table-header">
                        <i class="el-icon-coordinate header-icon" />
                        <span>重量</span>
                      </div>
                    </template>
                    <template slot-scope="scope">
                      <div class="weight-input-group">
                        <el-input v-model="scope.row.weight" placeholder="250.000" class="spec-input" />
                        <el-select
                          v-model="scope.row.weightUnit"
                          placeholder="克(g)"
                          class="weight-select"
                          style="width: 100px"
                        >
                          <el-option
                            v-for="item in (weight || [])"
                            :key="item.dictValue"
                            :label="item.dictLabel"
                            :value="item.dictLabel"
                          />
                        </el-select>
                      </div>
                    </template>
                  </el-table-column>

                  <el-table-column label="货品单位" min-width="100">
                    <template slot="header">
                      <div class="custom-table-header">
                        <i class="el-icon-box header-icon" />
                        <span>货品单位</span>
                      </div>
                    </template>
                    <template slot-scope="scope">
                      <el-select v-model="scope.row.salesUnit" placeholder="个" class="spec-select">
                        <el-option
                          v-for="item in (unitsGood || [])"
                          :key="item.dictValue"
                          :label="item.dictLabel"
                          :value="item.dictLabel"
                        />
                      </el-select>
                    </template>
                  </el-table-column>

                  <el-table-column prop="salesUnit" label="商品售卖单位" min-width="180">
                    <template slot="header">
                      <div class="custom-table-header">
                        <i class="el-icon-shopping-cart-2 header-icon" />
                        <span>商品售卖单位</span>
                      </div>
                    </template>
                    <template slot-scope="scope">
                      <el-select v-model="scope.row.salesUnit" placeholder="个" disabled class="spec-select unit-disabled" />
                    </template>
                  </el-table-column>

                  <el-table-column prop="barcode" label="商品条码（UPC）" min-width="250" class-name="required-column">
                    <template slot="header">
                      <div class="custom-table-header">
                        <i class="el-icon-postcard header-icon" />
                        <span class="required-label">商品条码（UPC）</span>
                        <el-tooltip content="商品条码是商品的唯一标识，用于商品的追溯和管理" placement="top" popper-class="custom-tooltip">
                          <i class="el-icon-question" />
                        </el-tooltip>
                      </div>
                    </template>
                    <template slot-scope="scope">
                      <div class="barcode-input-group">
                        <el-input v-model="scope.row.barcode" placeholder="建议输入商品包装上的条码" class="spec-input" />
                      </div>
                    </template>
                  </el-table-column>

                  <el-table-column prop="packageNumber" label="包装号" min-width="150">
                    <template slot="header">
                      <div class="custom-table-header">
                        <i class="el-icon-collection-tag header-icon" />
                        <span>包装号</span>
                        <el-tooltip
                          content="可用于隐私包装等再包装场景，可输入汉字、字母、数字和特殊符号，长度限制最多40位（小写字母会自动转为大写）"
                          placement="top"
                          popper-class="custom-tooltip"
                        >
                          <i class="el-icon-question" />
                        </el-tooltip>
                      </div>
                    </template>
                    <template slot-scope="scope">
                      <el-input v-model="scope.row.packageNumber" placeholder="" class="spec-input" />
                    </template>
                  </el-table-column>

                  <!-- 税收类目：下拉框 -->
                  <el-table-column prop="taxCategory" label="税收类目" min-width="150">
                    <template slot="header">
                      <div class="custom-table-header">
                        <i class="el-icon-office-building header-icon" />
                        <span>税收类目</span>
                      </div>
                    </template>
                    <template slot-scope="scope">
                      <el-select v-model="scope.row.taxCategory" placeholder="请选择" class="spec-select" />
                    </template>
                  </el-table-column>
                  <!-- 进项税：下拉框 -->
                  <el-table-column prop="inputTaxRate" label="进项税" min-width="150">
                    <template slot="header">
                      <div class="custom-table-header">
                        <i class="el-icon-arrow-down header-icon" />
                        <span>进项税</span>
                      </div>
                    </template>
                    <template slot-scope="scope">
                      <el-select v-model="scope.row.inputTaxRate" placeholder="请选择" class="spec-select" />
                    </template>
                  </el-table-column>
                  <!-- 销项税：下拉框 -->
                  <el-table-column prop="outputTaxRate" label="销项税" min-width="150">
                    <template slot="header">
                      <div class="custom-table-header">
                        <i class="el-icon-arrow-up header-icon" />
                        <span>销项税</span>
                      </div>
                    </template>
                    <template slot-scope="scope">
                      <el-select v-model="scope.row.outputTaxRate" placeholder="请选择" class="spec-select" />
                    </template>
                  </el-table-column>
                  <!-- 总部零售价：numberinput输入框 -->
                  <el-table-column prop="headquartersRetailPrice" label="总部零售价" min-width="210">
                    <template slot="header">
                      <div class="custom-table-header">
                        <i class="el-icon-money header-icon" />
                        <span>总部零售价</span>
                      </div>
                    </template>
                    <template slot-scope="scope">
                      <el-input-number
                        v-model="scope.row.headquartersRetailPrice"
                        controls-position="right"
                        :min="1"
                        class="price-input"
                      />
                    </template>
                  </el-table-column>
                  <!-- 外部编码 -->
                  <el-table-column prop="externalCode" label="外部编码" min-width="150">
                    <template slot="header">
                      <div class="custom-table-header">
                        <i class="el-icon-connection header-icon" />
                        <span>外部编码</span>
                      </div>
                    </template>
                    <template slot-scope="scope">
                      <el-input v-model="scope.row.externalCode" class="spec-input" />
                    </template>
                  </el-table-column>

                  <el-table-column label="操作" width="60" align="center">
                    <template slot="header">
                      <div class="custom-table-header">
                        <i class="el-icon-s-operation header-icon" />
                      </div>
                    </template>
                    <template slot-scope="scope">
                      <el-button
                        type="danger"
                        icon="el-icon-delete"
                        circle
                        size="mini"
                        class="delete-btn"
                        :disabled="form.productSkus.length <= 1"
                        @click="deleteSpec(scope.$index)"
                      />
                    </template>
                  </el-table-column>
                </el-table>
              </div>

              <div class="spec-summary">
                <span class="spec-count">共 {{ form.productSkus.length }} 条规格</span>
                <div class="spec-tips">
                  <i class="el-icon-info tips-icon" />
                  <span>完整填写规格信息有助于提高商品曝光度和转化率</span>
                </div>
              </div>
            </el-tab-pane>

            <!-- 详情信息 -->
            <el-tab-pane label="详情信息" name="detail">
              <div class="tab-header">
                <i class="el-icon-document tab-icon" />
                <span class="tab-title">商品详细信息</span>
                <div class="tab-line" />
              </div>

              <div class="detail-section">
                <el-form-item label="商品属性" prop="attributes">
                  <div class="attr-container">
                    <div class="attr-header">
                      <i class="el-icon-collection-tag" />
                      <span>属性信息</span>
                      <el-tooltip content="根据商品类目自动匹配相关属性" placement="top">
                        <i class="el-icon-question" />
                      </el-tooltip>
                    </div>
                    <el-row :gutter="16">
                      <el-col v-for="(attribute, index) in categoryAttributess || []" :key="index" :span="8">
                        <div class="attr-item">
                          <div class="attr-label" :class="{ required: attribute.required }">
                            <i class="el-icon-price-tag attr-icon" />
                            {{ attribute.name }}:
                          </div>

                          <el-col v-if="attribute.type === 1" :span="24">
                            <el-input
                              :value="getAttributeValue(attribute.name)"
                              @input="val => setAttributeValue(attribute.name, val)"
                              placeholder="请输入内容"
                              class="attr-input enhanced-input"
                              size="small"
                            />
                          </el-col>

                          <el-col v-if="attribute.type === 3" :span="24">
                            <el-select
                              :value="getAttributeValue(attribute.name)"
                              @change="val => setAttributeValue(attribute.name, val)"
                              placeholder="请选择"
                              class="attr-select enhanced-input"
                              size="small"
                            >
                              <el-option
                                v-for="(option, optionIndex) in attribute.options || []"
                                :key="optionIndex"
                                :label="option"
                                :value="option"
                              />
                            </el-select>
                          </el-col>

                          <el-col v-if="attribute.type === 4" :span="24">
                            <el-select
                              :value="getAttributeValue(attribute.name) || []"
                              @change="val => setAttributeValue(attribute.name, val)"
                              multiple
                              placeholder="请选择"
                              class="attr-select enhanced-input"
                              size="small"
                            >
                              <el-option
                                v-for="(option, optionIndex) in attribute.options || []"
                                :key="optionIndex"
                                :label="option"
                                :value="option"
                              />
                            </el-select>
                          </el-col>
                        </div>
                      </el-col>
                    </el-row>
                  </div>
                </el-form-item>

                <el-form-item label="图片详情" prop="detailImages">
                  <div class="detail-image-header">
                    <i class="el-icon-picture" />
                    <span>详情图片</span>
                    <div class="image-tip">高质量图片可以提高商品转化率</div>
                  </div>
                  <div class="detail-image-uploader">
                    <el-upload
                      action="#"
                      list-type="picture-card"
                      :auto-upload="false"
                      :file-list="form.detailImages"
                      :on-change="(file, fileList) => handleImageChange(file, fileList, 'detailImages')"
                      class="compact-upload"
                    >
                      <i class="el-icon-plus" />
                    </el-upload>
                  </div>
                  <div class="upload-tip">
                    <i class="el-icon-info tip-icon" />
                    <span>支持jpg、png格式，单张5MB以内</span>
                  </div>
                </el-form-item>
              </div>
            </el-tab-pane>
          </el-tabs>
        </el-form>
      </div>
    </div>

    <div slot="footer" class="dialog-footer">
      <el-button class="cancel-btn" @click="$emit('update:visible', false)">
        <i class="el-icon-close" />
        取 消
      </el-button>
      <el-button type="primary" class="submit-btn" @click="submitForm">
        <i class="el-icon-check" />
        保存商品
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import { productCategoryTree, meituanTree, getCategoryAttributesById } from '@/api/business/goodForm'
import { getToken } from '@/utils/auth'

export default {
  name: 'GoodForm',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    isEdit: {
      type: Boolean,
      default: false
    },
    goodData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      brand: [],
      weight: [],
      unitsGood: [],
      uploadImgUrl: process.env.VUE_APP_BASE_API + '/common/upload', // 若依上传接口
      headers: { Authorization: 'Bearer ' + getToken() },
      activeTab: 'basic',
      showMoreAttrs: false,
      form: {
        attributes: {},
        id: undefined,
        name: '',
        barcode: '',
        goodsType: 3, // 默认非标品
        specType: 1, // 默认多规格商品
        category: '',
        brand: '',
        origin: '',
        channelCategory: '',
        meituanAttr: '',
        sleeveLength: '',
        material: '',
        pattern: '',
        marketTime: '',
        style: '',
        collarType: '',
        season: '',
        fitType: '',
        mainImages: [],
        packageImages: [],
        materialImages: [],
        video: '',
        productSkus: [{
          name: '527',
          weight: '250.000',
          weightUnit: '克(g)',
          unit: '个',
          sellUnit: '个',
          barcode: '',
          package: ''
        }],
        sellingPoints: '',
        description: '',
        detailImages: [],
        productCategoryTreeData: [], // 商品类目数组
        defaultProps: {
          children: 'children', // 子节点
          label: 'categoryName' // 显示的字段
        },
        meituanTreeData: [],
        categoryAttributes: [],
        categoryAttributess: []
      },
      rules: {
        name: [
          { required: true, message: '商品名称不能为空', trigger: 'blur' }
        ],
        barcode: [
          { required: true, message: '商品条码不能为空', trigger: 'blur' }
        ],
        categoryIds: [
          { required: true, message: '商品类目不能为空', trigger: 'blur' }
        ],
        // brand: [
        //   { required: true, message: '品牌不能为空', trigger: 'blur' }
        // ],
        goodsType: [
          { required: true, message: '商品类型不能为空', trigger: 'change' }
        ],
        channelCategory: [
          { required: true, message: '渠道类目不能为空', trigger: 'change' }
        ]
      }
    }
  },
  watch: {
    form: {
      handler(val) {
        ['mainImage', 'mainImageTwo', 'mainImageThree'].forEach(key => {
          if (typeof val[key] === 'string') {
            this.form[key] = val[key].split(',').map(url => ({ name: url, url }))
          }
        })
      },
      deep: true
    },
    visible(val) {
      if (val && this.isEdit) {
        // Initialize form data when opening in edit mode
        this.initFormData()
      } else if (val && !this.isEdit) {
        // Reset form when opening in create mode
        this.resetForm()
      } else if (!val) {
        // Dialog is closing - just emit close event
        // Do NOT reset state here - will be done on next open
        this.$emit('close')
      }
    }
  },
  created() {
    console.log('GoodForm component created')
    // Make sure form.attributes is initialized
    if (!this.form.attributes) {
      console.log('Initializing form.attributes in created hook')
      this.$set(this.form, 'attributes', {})
    }
    // Initialize categoryAttributess as an empty array if not defined
    if (!this.form.categoryAttributess) {
      console.log('Initializing form.categoryAttributess in created hook')
      this.$set(this.form, 'categoryAttributess', [])
    }

    this.getDicts('brand').then(res => {
      this.brand = res.data
    })

    this.getDicts('units_good').then(res => {
      this.unitsGood = res.data
    })

    this.getDicts('weight').then(res => {
      this.weight = res.data
    })

    // Add diagnostic log to check form structure
    console.log('Initial form structure:', this.form)
    console.log('Initial productSkus:', this.form.productSkus)

    // Ensure productSkus is reactive
    if (this.form.productSkus) {
      this.form.productSkus = [...this.form.productSkus]
    } else {
      console.error('productSkus is not defined in form!')
      this.$set(this.form, 'productSkus', [{
        name: '',
        specification: '',
        weight: '',
        weightUnit: '克(g)',
        salesUnit: '个',
        barcode: '',
        package: ''
      }])
    }

    this.getList()
  },
  methods: {
    handleUploadSuccess(res, file, type) {
      if (res.code === 200) {
        const imageUrl = res.url || process.env.VUE_APP_BASE_API + res.fileName

        if (!this.form[type]) {
          this.$set(this.form, type, [])
        }

        this.form[type].push({ name: res.fileName, url: imageUrl })

        this.form[type] = [...this.form[type]]
      } else {
        this.$message.error('上传失败：' + res.msg)
      }
    },
    handleRemove(file, fileList, type) {
      this.form[type] = fileList
    },
    handleNameChange() {
      const matchedCategory = this.findCategoryByName(this.form.name, this.meituanTreeData)
      if (matchedCategory) {
        const fullCategoryPath = this.getFullCategoryPath(matchedCategory)
        this.form.meituanAttr = fullCategoryPath.map(item => item.id)

        this.fetchCategoryAttributes(matchedCategory.id)
      }
    },
    getFullCategoryPath(category) {
      const path = []
      let currentCategory = category

      while (currentCategory) {
        path.unshift(currentCategory)
        currentCategory = this.findCategoryById(currentCategory.parentId)
      }

      return path
    },
    findCategoryById(id) {
      const findCategory = (categories) => {
        for (const category of categories) {
          if (category.id === id) {
            return category
          }
          if (category.children) {
            const found = findCategory(category.children)
            if (found) return found
          }
        }
        return null
      }

      return findCategory(this.meituanTreeData)
    },
    findCategoryByName(name, categories) {
      for (const category of categories) {
        if (category.name && name.includes(category.name)) {
          return category
        }
        if (category.children) {
          const matchedChild = this.findCategoryByName(name, category.children)
          if (matchedChild) return matchedChild
        }
      }
      return null
    },
    handleCategoryChange(node, checked) {
      if (checked) {
        this.form.category = node.id
      } else {
        this.form.category = null
      }
    },
    fetchCategoryAttributes(categoryId) {
      // Initialize attributes as empty object to prevent null reference errors
      if (!this.form.attributes) {
        this.$set(this.form, 'attributes', {})
      }
      getCategoryAttributesById(categoryId)
        .then(response => {
          console.log('类目属性数据:', response)
          if (response && response.data) {
            this.categoryAttributes = response.data.map(attr => ({
              ...attr,
              options: attr.options ? JSON.parse(attr.options) : []
            }))
            this.categoryAttributess = this.categoryAttributes || []
            // Ensure form.attributes is properly initialized
            if (!this.form.attributes) {
              this.$set(this.form, 'attributes', {})
            }
            // Pre-initialize attributes with empty values
            this.categoryAttributess.forEach(attr => {
              if (!this.form.attributes[attr.name]) {
                this.$set(this.form.attributes, attr.name, '')
              }
            })
          } else {
            console.warn('No data returned from getCategoryAttributesById')
            this.categoryAttributes = []
            this.categoryAttributess = []
          }
        })
        .catch(error => {
          console.error('获取类目属性失败:', error)
          this.categoryAttributess = []
        })
    },
    getList() {
      productCategoryTree({}).then(res => {
        this.productCategoryTreeData = res.data
        this.filterEmptyChildren(this.productCategoryTreeData)
      })

      meituanTree({}).then(res => {
        this.meituanTreeData = res.data
        this.filterEmptyChildren(this.meituanTreeData)
      })
    },
    filterEmptyChildren(categories) {
      const filterChildren = (categories) => {
        return categories
          .map(category => {
            if (category.children && category.children.length > 0) {
              category.children = filterChildren(category.children)
              return category
            } else {
              delete category.children
              return category
            }
          })
          .filter(category => category.children || category.children === undefined)
      }

      return filterChildren(categories)
    },
    initFormData() {
      this.form = JSON.parse(JSON.stringify(this.goodData))

      console.log('this,form', this.form)

      this.form.mainImage = this.form.mainImage ? this.form.mainImage.split(',').map(url => ({ name: url, url })) : []
      this.form.mainImageTwo = this.form.mainImageTwo ? this.form.mainImageTwo.split(',').map(url => ({ name: url, url })) : []
      this.form.mainImageThree = this.form.mainImageThree ? this.form.mainImageThree.split(',').map(url => ({ name: url, url })) : []

      if (typeof this.form.categoryId === 'string') {
        this.form.categoryIds = this.form.categoryId.split(',').map(Number)
      }

      if (typeof this.form.meituanChannelId === 'string') {
        this.form.meituanAttr = this.form.meituanChannelId.split(',').map(Number)
      }
      this.form.isStandard = this.goodData.isStandard === '标品' ? 1 : 2

      if (this.form.meituanAttr && this.form.meituanAttr.length > 0) {
        this.fetchCategoryAttributes(this.form.meituanAttr[this.form.meituanAttr.length - 1])
      }

      if (typeof this.form.attributes === 'string') {
        try {
          this.form.attributes = JSON.parse(this.form.attributes)
        } catch (e) {
          console.error('解析 attributes 失败:', e)
          this.form.attributes = {}
        }
      }
      console.log('this,form', this.form)
    },
    resetForm() {
      this.form = {
        id: undefined,
        name: '',
        barcode: '',
        goodsType: 3,
        specType: 1,
        category: '',
        brand: '',
        origin: '',
        channelCategory: '',
        meituanAttr: '',
        sleeveLength: '',
        material: '',
        pattern: '',
        marketTime: '',
        style: '',
        collarType: '',
        season: '',
        fitType: '',
        mainImages: [],
        packageImages: [],
        materialImages: [],
        video: '',
        productSkus: [{
          name: '',
          specification: '',
          weight: '',
          weightUnit: '克(g)',
          unit: '个',
          sellUnit: '个',
          salesUnit: '个',
          barcode: '',
          package: '',
          packageNumber: '',
          taxCategory: '',
          inputTaxRate: '',
          outputTaxRate: '',
          headquartersRetailPrice: 0,
          externalCode: ''
        }],
        detail: {
          attributes: '',
          images: []
        },
        attributes: {},
        sellingPoints: '',
        description: '',
        detailImages: [],
        productCategoryTreeData: [],
        defaultProps: {
          children: 'children',
          label: 'categoryName'
        },
        meituanTreeData: [],
        categoryAttributes: [],
        categoryAttributess: []
      }

      if (this.$refs.form) {
        this.$refs.form.resetFields()
      }
    },
    addSpec() {
      const newSpec = {
        name: '',
        specification: '',
        weight: '',
        weightUnit: '克(g)',
        unit: '个',
        sellUnit: '个',
        salesUnit: '个',
        barcode: '',
        packageNumber: '',
        taxCategory: '',
        inputTaxRate: '',
        outputTaxRate: '',
        headquartersRetailPrice: 0,
        externalCode: '',
        // Make sure we have all the fields that are expected in the table
        package: ''
      }

      console.log('Current specifications:', JSON.stringify(this.form.productSkus))
      this.form.productSkus.push(newSpec)
      console.log('After adding new spec:', JSON.stringify(this.form.productSkus))

      this.$nextTick(() => {
        // Force the table to update by creating a new array reference
        this.form.productSkus = [...this.form.productSkus]
        console.log('Array updated via nextTick')
      })
    },
    deleteSpec(index) {
      if (this.form.productSkus.length > 1) {
        this.form.productSkus.splice(index, 1)
      } else {
        this.$message.warning('至少保留一个规格')
      }
    },
    handleImageChange(file, fileList, imageType) {
      this.form[imageType] = fileList
    },
    handleVideoChange(file) {
      if (file.raw.size > 10 * 1024 * 1024) {
        this.$message.error('视频大小不能超过10MB')
        return
      }

      const isVideo = ['video/mp4', 'video/mov', 'video/wmv', 'video/avi', 'video/mpg', 'video/mpeg'].includes(file.raw.type)
      if (!isVideo) {
        this.$message.error('请上传正确的视频格式')
        return
      }

      this.form.video = URL.createObjectURL(file.raw)
    },
    toggleMoreAttrs() {
      this.showMoreAttrs = true
    },
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          const submitData = {
            ...this.form
          }
          this.$emit('submit', submitData)
        }
      })
    },
    handleClose() {
      this.$emit('update:visible', false)
      // Reset form state when dialog closes
      if (this.$refs.form) {
        this.$refs.form.resetFields()
      }
      // Reset other component state
      this.activeTab = 'basic'
      this.showMoreAttrs = false
    },
    addAttribute() {
      this.$message.info('属性功能暂未实现')
    },
    getRowClass({ row, rowIndex }) {
      return rowIndex % 2 === 0 ? 'even-row' : 'odd-row'
    },
    debugAddSpec() {
      console.log('Debug add spec called')
      // Create a very simple spec with minimal properties
      const debugSpec = {
        specification: '测试规格 ' + (this.form.productSkus.length + 1),
        weight: '100',
        weightUnit: '克(g)',
        salesUnit: '个',
        headquartersRetailPrice: 10
      }

      // Add directly to the array
      this.form.productSkus.push(debugSpec)

      // Force update
      this.$forceUpdate()
      console.log('Added debug spec, new length:', this.form.productSkus.length)

      // Show confirmation
      this.$message.success('已添加测试规格，当前共 ' + this.form.productSkus.length + ' 条规格')
    },
    getAttributeValue(attributeName) {
      if (!this.form.attributes) {
        console.log('Initializing form.attributes in getAttributeValue')
        this.$set(this.form, 'attributes', {})
      }
      const value = this.form.attributes[attributeName] || ''
      console.log(`Getting attribute ${attributeName}: ${value}`)
      return value
    },
    setAttributeValue(attributeName, value) {
      if (!this.form.attributes) {
        console.log('Initializing form.attributes in setAttributeValue')
        this.$set(this.form, 'attributes', {})
      }
      console.log(`Setting attribute ${attributeName} to: ${value}`)
      this.$set(this.form.attributes, attributeName, value)
    }
  }
}
</script>

<style scoped>
.compact-dialog {
  --primary-color: #409EFF;
  --secondary-color: #67C23A;
  --warning-color: #E6A23C;
  --danger-color: #F56C6C;
  --info-color: #909399;
  --border-color: #DCDFE6;
  --border-radius: 4px;
  --bg-light: #F5F7FA;
  --bg-lighter: #FAFBFC;
  --spec-header-bg: linear-gradient(to right, #e8f1fd, #e2f0ff);
  --spec-odd-row: #f9fbff;
  --spec-even-row: #ffffff;
  --spec-hover-row: #f0f7ff;
}

.good-form-container {
  margin: 0;
  padding: 0;
}

.form-section {
  margin: 0;
  background: #fff;
  border-radius: var(--border-radius);
}

/* 主标签页样式 */
::v-deep .main-tabs {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  border-radius: 4px;
  margin-bottom: 20px;
}

::v-deep .main-tabs .el-tabs__header {
  margin: 0;
  background: linear-gradient(to right, #f8f9fb, #edf1f7);
  border-radius: 4px 4px 0 0;
}

::v-deep .main-tabs .el-tabs__item {
  height: 42px;
  line-height: 42px;
  font-size: 14px;
  color: #606266;
  transition: all 0.3s;
  padding: 0 20px;
}

::v-deep .main-tabs .el-tabs__item.is-active {
  color: var(--primary-color);
  font-weight: 600;
  background: #fff;
  position: relative;
}

::v-deep .main-tabs .el-tabs__item.is-active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 20px;
  right: 20px;
  height: 3px;
  background: var(--primary-color);
  border-radius: 2px;
}

::v-deep .main-tabs .el-tabs__nav-wrap::after {
  height: 1px;
  background-color: #e6e6e6;
}

::v-deep .main-tabs .el-tabs__content {
  padding: 20px;
}

/* 两列布局 */
.form-grid {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.form-column {
  flex: 1;
  min-width: 0;
}

/* 表单元素通用样式 */
::v-deep .el-form-item {
  margin-bottom: 18px;
}

::v-deep .el-form-item__label {
  font-size: 13px;
  line-height: 40px;
  padding-right: 8px;
}

::v-deep .el-input__inner,
::v-deep .el-textarea__inner {
  font-size: 13px;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
  line-height: 1.4;
}

/* 上传组件样式 */
.upload-group {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.upload-item {
  flex: 1;
  min-width: 100px;
  max-width: 32%;
  margin-bottom: 8px;
}

.upload-label {
  font-size: 12px;
  color: #606266;
  margin-bottom: 6px;
  padding-left: 2px;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

/* 压缩上传组件大小 */
::v-deep .compact-upload .el-upload--picture-card {
  width: 80px;
  height: 80px;
  line-height: 80px;
  border-radius: 4px;
  border: 1px dashed #cfd3dc;
  transition: all 0.3s;
}

::v-deep .compact-upload .el-upload--picture-card:hover {
  border-color: var(--primary-color);
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

::v-deep .compact-upload .el-upload-list--picture-card .el-upload-list__item {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  margin: 0 8px 8px 0;
}

/* 视频上传样式 */
.video-uploader {
  width: 120px;
  height: 120px;
}

.upload-video-placeholder {
  width: 120px;
  height: 120px;
  border: 1px dashed var(--border-color);
  border-radius: var(--border-radius);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  background-color: var(--bg-light);
  transition: all 0.3s;
}

.upload-video-placeholder:hover {
  border-color: var(--primary-color);
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.video-container {
  width: 120px;
  height: 120px;
  border: 1px solid var(--border-color);
  border-radius: var(--border-radius);
  overflow: hidden;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.video-container video {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 规格表单样式 */
.spec-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding: 12px 15px;
  background: linear-gradient(135deg, #f0f5ff, #e6f7ff);
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  border-left: 4px solid var(--primary-color);
  position: relative;
  overflow: hidden;
}

.spec-header::before {
  content: '';
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  width: 100px;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.5));
  z-index: 1;
}

.spec-type {
  display: flex;
  align-items: center;
  font-weight: 500;
}

.spec-icon {
  font-size: 20px;
  color: var(--primary-color);
  margin-right: 8px;
  background: rgba(64, 158, 255, 0.1);
  padding: 8px;
  border-radius: 8px;
}

.button-group {
  display: flex;
  gap: 10px;
}

.add-spec-btn {
  font-weight: 500;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 8px 16px;
  border-radius: 20px;
  transition: all 0.3s;
  background: linear-gradient(135deg, #409EFF, #64b0ff);
  border: none;
  box-shadow: 0 4px 10px rgba(64, 158, 255, 0.2);
  cursor: pointer;
}

.add-spec-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 12px rgba(64, 158, 255, 0.3);
}

.add-spec-btn i,
.add-spec-btn span {
  pointer-events: none; /* Ensures clicks on icon/text bubble up to button */
}

.add-spec-btn i {
  margin-right: 4px;
  font-size: 14px;
}

.spec-table-wrapper {
  margin-bottom: 20px;
  overflow-x: auto;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border: 1px solid #ebeef5;
  background: white;
}

.spec-table-header {
  padding: 12px 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: linear-gradient(to right, #f8f9fc, #f0f3fa);
  border-bottom: 1px solid #ebeef5;
}

.header-title-wrapper {
  display: flex;
  align-items: center;
}

.header-title-wrapper i {
  font-size: 16px;
  color: var(--primary-color);
  margin-right: 8px;
}

.dialog-footer{
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.header-title {
  font-size: 15px;
  font-weight: 600;
  color: #303133;
  display: flex;
  align-items: center;
}

.header-title::before {
  content: '';
  width: 4px;
  height: 16px;
  background: var(--primary-color);
  border-radius: 2px;
  margin-right: 8px;
  display: inline-block;
}

.header-actions {
  color: #909399;
}

.custom-table-header {
  display: flex;
  align-items: center;
  white-space: nowrap;
}

.header-icon {
  margin-right: 4px;
  font-size: 14px;
  color: #5c87b5;
}

.spec-table {
  width: 100%;
  font-size: 12px;
  margin: 0 !important;
}

::v-deep .spec-table th {
  padding: 12px 8px;
  position: relative;
}

::v-deep .spec-table th::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  width: 0;
  height: 3px;
  background: linear-gradient(90deg, #4e94eb, #7db7ff);
  border-radius: 3px;
  transition: all 0.3s;
  transform: translateX(-50%);
}

::v-deep .spec-table th:hover::after {
  width: 40px;
}

::v-deep .spec-table .odd-row {
  background-color: var(--spec-odd-row);
}

::v-deep .spec-table .even-row {
  background-color: var(--spec-even-row);
}

::v-deep .spec-table tr:hover td {
  background-color: var(--spec-hover-row) !important;
}

::v-deep .spec-table td {
  padding: 8px;
  transition: all 0.2s;
}

.spec-input, .spec-select, .price-input {
  font-size: 12px !important;
}

::v-deep .spec-input .el-input__inner,
::v-deep .spec-select .el-input__inner {
  height: 32px;
  line-height: 32px;
  border-radius: 4px;
  padding: 0 10px;
  font-size: 12px;
  transition: all 0.25s;
  border-color: #dcdfe6;
}

::v-deep .spec-input .el-input__inner:focus,
::v-deep .spec-select .el-input__inner:focus {
  border-color: var(--primary-color);
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

::v-deep .unit-disabled .el-input__inner {
  background-color: #f5f7fa;
  color: #606266;
}

::v-deep .price-input {
  width: 100%;
}

::v-deep .price-input .el-input__inner {
  color: #f56c6c;
  font-weight: 500;
}

::v-deep .weight-input-group {
  display: flex;
}

::v-deep .weight-input-group .el-input {
  border-top-right-radius: 0;
  border-bottom-right-radius: 0;
}

::v-deep .weight-select .el-input__inner {
  border-left: none;
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
}

.barcode-input-group {
  position: relative;
}

.barcode-input-group::before {
  content: '';
  position: absolute;
  left: -12px;
  top: 0;
  bottom: 0;
  width: 3px;
  background-color: var(--primary-color);
  opacity: 0.7;
  border-radius: 2px;
}

.delete-btn {
  transition: all 0.3s;
  width: 32px;
  height: 32px;
  font-size: 12px;
  padding: 0;
}

.delete-btn:not(:disabled):hover {
  transform: rotate(90deg);
  background-color: #ff4949;
}

.spec-summary {
  display: flex;
  justify-content: space-between;
  padding: 12px 16px;
  background: #f8f9fb;
  border-radius: 6px;
  margin-top: 10px;
  border: 1px dashed #d9e1ec;
}

.spec-count {
  color: #606266;
  font-weight: 500;
}

.spec-tips {
  display: flex;
  align-items: center;
  color: #909399;
  font-size: 12px;
}

.tips-icon {
  color: var(--warning-color);
  margin-right: 6px;
  font-size: 14px;
}

/* Custom tooltip styling */
.custom-tooltip {
  max-width: 220px !important;
  white-space: normal !important;
  line-height: 1.5 !important;
  padding: 10px !important;
  font-size: 12px !important;
  background: #252525 !important;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15) !important;
}

::v-deep .el-tooltip__popper[x-placement^="top"] .popper__arrow {
  border-top-color: #252525 !important;
}

::v-deep .el-tooltip__popper[x-placement^="top"] .popper__arrow::after {
  border-top-color: #252525 !important;
}

/* ... rest of existing styles ... */
</style>

<style>
.custom-tooltip {
  max-width: 200px !important;
  white-space: normal !important;
  line-height: 1.4 !important;
}

.tab-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.tab-icon {
  font-size: 20px;
  color: var(--primary-color);
  background: rgba(64, 158, 255, 0.1);
  border-radius: 8px;
  padding: 8px;
  margin-right: 10px;
}

.tab-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.tab-line {
  flex: 1;
  height: 3px;
  background: linear-gradient(to right, rgba(64, 158, 255, 0.2), transparent);
  margin-left: 15px;
  border-radius: 3px;
}

.input-with-icon {
  display: flex;
  align-items: center;
}

.form-item-icon {
  font-size: 16px;
  color: var(--primary-color);
  margin-right: 8px;
  background: rgba(64, 158, 255, 0.1);
  padding: 6px;
  border-radius: 4px;
  min-width: 28px;
  text-align: center;
}

.enhanced-input {
  flex: 1;
}

.form-tip {
  margin-top: 5px;
  font-size: 12px;
  color: #909399;
  display: flex;
  align-items: center;
}

.tip-icon {
  color: var(--warning-color);
  margin-right: 4px;
  font-size: 14px;
}

/* Styles for other form items */
::v-deep .el-form-item.is-required .el-form-item__label::before {
  content: '';
  color: #F56C6C;
  margin-right: 4px;
}

::v-deep .el-form-item.is-required .form-item-icon::after {
  content: '*';
  color: #F56C6C;
  position: absolute;
  top: 2px;
  right: 2px;
  font-size: 14px;
}

::v-deep .el-input.enhanced-input .el-input__inner {
  border-radius: 4px;
  transition: all 0.3s;
}

::v-deep .el-input.enhanced-input .el-input__inner:focus {
  border-color: var(--primary-color);
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

::v-deep .el-select.enhanced-input .el-input__inner:focus {
  border-color: var(--primary-color);
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

::v-deep .el-cascader.enhanced-input .el-input__inner:focus {
  border-color: var(--primary-color);
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.attr-container {
  background: #f8fafc;
  border-radius: 8px;
  padding: 15px;
  border: 1px solid #ebeef5;
  margin-bottom: 20px;
}

.attr-header {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
  font-weight: 600;
  color: #303133;
}

.attr-header i {
  color: var(--primary-color);
  margin-right: 5px;
  font-size: 16px;
}

.attr-header .el-icon-question {
  margin-left: 5px;
  color: #909399;
  cursor: pointer;
  font-size: 14px;
}

.attr-item {
  background: white;
  border-radius: 4px;
  padding: 12px;
  margin-bottom: 10px;
  border: 1px solid #ebeef5;
  transition: all 0.3s;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.02);
}

.attr-item:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  border-color: #d6e4ff;
}

.attr-label {
  margin-bottom: 8px;
  color: #606266;
  font-size: 13px;
  display: flex;
  align-items: center;
}

.attr-icon {
  font-size: 14px;
  color: var(--primary-color);
  margin-right: 5px;
  background: rgba(64, 158, 255, 0.1);
  padding: 4px;
  border-radius: 4px;
}

.attr-label.required:after {
  content: '*';
  color: #F56C6C;
  margin-left: 4px;
}

.detail-image-header {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.detail-image-header i {
  font-size: 18px;
  color: var(--primary-color);
  margin-right: 8px;
  background: rgba(64, 158, 255, 0.1);
  padding: 6px;
  border-radius: 4px;
}

.detail-image-header span {
  font-weight: 600;
  color: #303133;
}

.image-tip {
  margin-left: auto;
  font-size: 12px;
  color: #909399;
}

.detail-image-uploader {
  background: #f8fafc;
  border-radius: 8px;
  padding: 15px;
  border: 1px dashed #d0d7de;
}

.cancel-btn, .submit-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 10px 20px;
  transition: all 0.3s;
}

.cancel-btn i, .submit-btn i {
  margin-right: 5px;
  font-size: 14px;
}

.submit-btn {
  background: linear-gradient(135deg, #409EFF, #64b0ff);
  border: none;
  box-shadow: 0 4px 10px rgba(64, 158, 255, 0.2);
}

.submit-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 12px rgba(64, 158, 255, 0.3);
}
</style>
